package com.yohann.order_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.yohann.base.exception.IEnglishException;
import com.yohann.order_service.entity.Orders;
import com.yohann.order_service.entity.vo.OrderVo;
import com.yohann.order_service.service.OrdersService;
import com.yohann.order_service.service.WeChatPayService;
import com.yohann.order_service.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 微信支付业务实现
 * </p>
 *
 * @author Yohann
 * @since 2020/11/13 15:37
 */
@Service
public class WeChatPayServiceImpl implements WeChatPayService {
    @Autowired
    private OrdersService ordersService;

    /**
     * 生成支付二维码
     *
     * @param orderId
     * @return
     */
    @Override
    public Map getQrCode(String orderId) {
        //1.根据订单号查询订单信息
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, orderId);
        OrderVo orderInfo = ordersService.getOrderInfo(orderId);

        //2.使用map 生成微信二维码需要的参数
        Map<String, String> map = new HashMap();

        map.put("appid", "wx74862e0dfcf69954");
        map.put("mch_id", "1558950191");
        map.put("nonce_str", WXPayUtil.generateNonceStr());
        //课程标题
        map.put("body", orderInfo.getCourseName());
        //订单号
        map.put("out_trade_no", orderId);
        map.put("total_fee", orderInfo.getFee() + "");
        map.put("spbill_create_ip", "127.0.0.1");
        map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
        map.put("trade_type", "NATIVE");

        //3.发送httpclient请求，传递参数xml格式，微信支付提供的固定的地址
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

        try {
            //设置xml格式的参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);

            //执行post请求发送
            client.post();

            //4.得到发送请求返回的内容
            //返回内容 是使用xml格式返回
            String xml = client.getContent();

            //把xml格式转换成map集合，把map集合返回
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //最终返回数据 的封装
            Map dataMap = new HashMap();
            dataMap.put("out_trade_no", orderId);
            dataMap.put("course_id", orderInfo.getCourseId() + "");
            dataMap.put("total_fee", orderInfo.getFee() + "");

            //返回二维码操作状态码
            dataMap.put("result_code", resultMap.get("result_code"));

            //二维码地址
            dataMap.put("code_url", resultMap.get("code_url"));

            return dataMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new IEnglishException(20001, "生成支付二维码失败");
        }
    }

    /**
     * 查询支付状态
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> getPayStatus(String orderId) {
        //1、封装参数
        Map m = new HashMap<>(16);
        m.put("appid", "wx74862e0dfcf69954");
        m.put("mch_id", "1558950191");
        m.put("out_trade_no", orderId);
        m.put("nonce_str", WXPayUtil.generateNonceStr());


        //2.发送httpClient
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        try {
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            //3.得到请求返回的内容
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //4.转成map返回
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 更新订单信息
     *
     * @param map
     */
    @Override
    public boolean updateOrderStatue(Map<String, String> map) {
        //从map中获取订单号
        String orderId = map.get("out_trade_no");

        //根据订单号查询订单信息
        Orders order = ordersService.getById(orderId);

        if(order.getState()){
            return true;
        }

        //设置支付状态
        order.setState(true);
        //设置支付时间
        order.setPayTime(new Date());

        //更新支付状态
        return ordersService.updateById(order);
    }
}